import { _decorator, Component, Node, misc, Vec3, Vec2, SkeletalAnimation, animation } from 'cc';
import EventManager from '../core/event-manager';
import { AnimationStateController } from './animimation-state-controller';
const { ccclass, property } = _decorator;

@ccclass('PlayerController')
export class PlayerController extends Component {
    @property({ type: Node })
    nodeCamera: Node = null!;
    @property({ type: animation.AnimationController })
    animationController: animation.AnimationController = null!;



    private _isMove: boolean = false;
    private _speed: number = 0.05;
    private _angle: number = 0;

    private _playerPosition: Vec3 = null;
    private _playerEulerAngle: Vec3 = null;
    private _cameraMountEulerAngle: Vec3 = null;

    private _sensitivity: Vec2 = new Vec2(0.1, 0.1);

    private _animationStateController: AnimationStateController = null!;

    start() {
        this.nodeCamera.eulerAngles = new Vec3(0, 0, 0);
        this._animationStateController = new AnimationStateController(this.animationController);
        EventManager.on("player-move-start", this.move, this);
        EventManager.on("player-move-end", this.stopMove, this);
    }
    public move(angle: number, isRun: boolean = false): void {
        if (isRun) {
            this._animationStateController.run(angle);
        } else {
            this._animationStateController.walk(angle);
        }
        this._isMove = true;
        this._angle = angle;
    }
    public stopMove(): void {
        this._isMove = false;
        this._animationStateController.idle();
    }
    public rotate(h: number, v: number): void {
        this._playerEulerAngle = this.node.eulerAngles;
        this._playerEulerAngle.y += -h * this._sensitivity.x;
        this.node.eulerAngles = this._playerEulerAngle;

        this._cameraMountEulerAngle = this.nodeCamera.eulerAngles;
        this._cameraMountEulerAngle.x -= v * this._sensitivity.y;
        if (this._cameraMountEulerAngle.x > 25) {
            this._cameraMountEulerAngle.x = 25;
        }
        if (this._cameraMountEulerAngle.x < -40) {
            this._cameraMountEulerAngle.x = -40;
        }


        this.nodeCamera.eulerAngles = this._cameraMountEulerAngle;
    }

    update(deltaTime: number) {
        this.updateMove();
    }
    public updateMove(): void {
        if (!this._isMove) return;
        let angle: number = this.node.eulerAngles.y;
        angle += this._angle;

        let radian: number = misc.degreesToRadians(angle);
        let x: number = this._speed * Math.sin(radian);
        let z: number = this._speed * Math.cos(radian);

        this._playerPosition = this.node.position;
        this._playerPosition.x += x;
        this._playerPosition.z += z;

        this.node.position = this._playerPosition;
    }
}


